import { Annotation } from "@langchain/langgraph";
import { exists } from "../utils/file";
import { read, Xlsx } from "../utils/xlsx";
import { OutputState } from "../utils/state";
import { log } from "../utils/logs";
import fs from 'fs';

export const XlsxParseState = Annotation.Root({
  root: Annotation<string>(), // 根目录
  file: Annotation<string>(), // 文件

  xlsx: Annotation<Xlsx>(), // 读取的xlsx文件
  xlsxList: Annotation<Xlsx[]>(), // 读取的xlsx文件

  ...OutputState.spec,
});

/**
 * 读取xlsx文件
 * @param state
 * @returns
 */
export const parse = async (state: typeof XlsxParseState.State) => {
  const { root, file } = state;
  let xlsx: Xlsx = {};
  try {
    if (!file) {
      return {
        ...state,
        xlsx,
      };
    }
    xlsx = await read(file, root);
    await log(file, 'xlsx.json', JSON.stringify(xlsx, null, 2))
  } catch (error) {
    console.error(`解析xlsx文件${file}出错：`, error);
  }
  return {
    ...state,
    xlsx,
  };
};

/**
 * 批读取xlsx文件
 * @param state
 */
export const batch = async (state: typeof XlsxParseState.State) => {
  let records: Xlsx[] = [];
  const { root } = state;
  try {
    if (!(await exists(root))) {
      return {
        ...state,
        xlsxList: records,
      };
    }
    const files = await fs.promises.readdir(root);
    const parse = async (file: string, cwd: string) => {
      return await read(file, cwd);
    };
    records = await Promise.all(files.map((file) => parse(file, root)));
  } catch (error) {
    console.error(`xlxs批处理出错：`, error);
  }
  return {
    ...state,
    xlsxList: records,
  };
};
